package user_roles

import (
	"fmt"
	"gitee.com/theegg/go-brick/app/model"
	"gitee.com/theegg/go-brick/app/model/partner/partner_admin/partner_admin_permissions"
	"gitee.com/theegg/go-brick/app/model/partner/partner_admin/partner_admin_role_users"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/cmap"
	"time"
)

// 查询参数
type UserRoleQueryParams struct {
	PageSize  string `form:"page_size" json:"page_size"  binding:"gte=0,lte=100" label:"每页数量"`
	PageIndex string `form:"page_index" json:"page_index"  binding:"gte=0,lte=99999" label:"当前页数"`
	Sign      string `form:"sign" json:"sign"  binding:"" label:"标识"`
}

// 添加角色的参数
type UserRoleAddParams struct {
	Ip   string
	Name string `form:"name" json:"name"  binding:"required,min=3,max=24" label:"角色名称"`
	Sign string `form:"sign" json:"sign"  binding:"required,min=3,max=24" label:"角色标识"`
	Mark string `form:"mark" json:"mark"  binding:"required,min=3,max=32" label:"角色备注"`

	AddAdminUserId int64  `form:"add_admin_user_id" json:"add_admin_user_id"  binding:"" label:"添加人"`
	AddAdminUserIp string `form:"add_admin_user_ip" json:"add_admin_user_ip"  binding:"" label:"添加人IP"`
}

var SupperRoleId int64 = 1

// 分页获取所有数据
// @param params map 参数
// @param pageSize int 每页数据量
// @return mix
func GetDataList(params map[string]interface{}) (map[string]interface{}, error) {
	returnData := make(map[string]interface{}, 0)

	queryParams, errBuild := model.BuildAdminQueryParam(params)
	if errBuild != nil {
		return nil, app.NewError(errBuild)
	}

	query := app.Db().Desc("id").Limit(queryParams.Limit, queryParams.Offset)

	// query sign
	if _, ok := queryParams.Params["sign"]; ok && queryParams.Params["sign"].(string) != "" {
		query.Where("sign = ?", queryParams.Params["sign"])
	}

	data := make([]UserRoles, 0)
	// 求总条数
	total, err := query.FindAndCount(&data)
	if err != nil {
		return nil, app.NewError(err)
	}

	returnData["data"] = data
	returnData["total"] = total

	return returnData, nil
}

// 添加角色
func AddRole(params UserRoleAddParams) (*UserRoles, error) {
	arNew := new(UserRoles)
	arNew.Name = params.Name
	arNew.Mark = params.Mark
	arNew.Sign = params.Sign
	arNew.AddAdminUserIp = params.AddAdminUserIp
	arNew.AddAdminUserId = params.AddAdminUserId

	arNew.CreatedAt = time.Now()

	affected, err := app.Db().Insert(arNew)

	if err != nil {
		return nil, err
	}

	if affected != 1 {
		return nil, fmt.Errorf("affect rows is less than one")
	}

	return arNew, nil
}

// @title ModifyStatus
// @description 修改管理员状态
func (ur *UserRoles) EditRoleInfo(params UserRoleAddParams) (bool, error) {

	affected, err := app.Db().Table(new(UserRoles)).ID(ur.Id).Cols("name", "mark").Update(map[string]string{"name": params.Name, "mark": params.Mark})

	if err != nil {
		return false, app.NewError(err)
	}

	// 生效条数
	if affected == 0 {
		return false, app.NewError("对不起, 更新未成功")
	}

	return true, nil
}

// @title ModifyStatus
// @description 修改管理员状态
func (ur *UserRoles) ModifyStatus() (bool, error) {
	status := !ur.State
	affected, err := app.Db().Table(new(UserRoles)).ID(ur.Id).Cols("state").Update(map[string]bool{"state": status})

	if err != nil {
		return false, app.NewError(err)
	}

	// 生效条数
	if affected == 0 {
		return false, app.NewError("对不起, 指定的ID更新数量不正确")
	}

	return true, nil
}

// @title EditRolePermissions
// @description 编辑角色的权限
func (ur *UserRoles) EditRolePermissions(targetRole *UserRoles, permissionIds map[int64]int64) (bool, error) {
	// 1. 获取当前角色 分配的　权限
	currentPermissions, errCm := partner_admin_permissions.GetAdminPermissionsByRoleIdFromDb(ur.Id, ur.IsSuperRole())
	if errCm != nil {
		return false, errCm
	}

	// 2. 检测　ID　是否是当前登陆用户的角色已经分配
	for _, id := range permissionIds {
		if _, ok := currentPermissions[id]; !ok {
			return false, app.NewError("无效的 permission Id")
		}
	}

	targetPermissions, errTp := partner_admin_permissions.GetAdminPermissionsByRoleIdFromDb(targetRole.Id, targetRole.IsSuperRole())
	if errTp != nil {
		return false, errTp
	}

	// 3. 遍历出哪些是新增
	addPermissionIds := make([]int64, 0)
	for _, id := range permissionIds {
		if _, ok := targetPermissions[id]; !ok {
			addPermissionIds = append(addPermissionIds, id)
		}
	}

	// 4. 遍历出哪些是移除
	removePermissionIds := make([]int64, 0)
	for tId, _ := range targetPermissions {
		if ok := cmap.IsValueInt64ExistMapInt64(tId, permissionIds); !ok {
			removePermissionIds = append(removePermissionIds, tId)
		}
	}

	return true, nil
}

// @title GetItemById
// @description 获取item从数据库
func GetItemById(roleId int64) (*UserRoles, error) {
	item := new(UserRoles)

	has, err := app.Db().ID(roleId).Get(item)

	if err != nil {
		return nil, app.NewError(err)
	}

	if !has {
		return nil, app.NewError("对不起, 未查询到相关数据")
	}

	return item, nil
}

// 获取所有 可用 的角色
func (ur UserRoles) GetAllRoles() (map[int64]UserRoles, error) {

	items := make(map[int64]UserRoles, 0)

	err := app.Db().Where("status = ?", true).Find(&items)
	if err != nil {
		return nil, app.NewError(err)
	}

	return items, nil
}

// 是不是超级角色
func (ur UserRoles) IsSuperRole() bool {
	return ur.Id == SupperRoleId
}

// 获取角色上分配的所有userIds
func (ur UserRoles) GetRoleBindUserIds() ([]int64, error) {
	ids, err := partner_admin_role_users.GetUserIdsByRoleId(ur.Id)
	if err != nil {
		return nil, app.NewError(err)
	}

	return ids, nil
}

/* ====================== 关联当前用户权限 ============================ */

// 关联当前用户权限
// @return map[int64]*partner_admin_permissions.PartnerAdminPermissions map类型
func (ur *UserRoles) Permissions() (map[int64]*partner_admin_permissions.PartnerAdminPermissions, error) {

	if ur.Id == 0 {
		return nil, app.NewError("对不起，角色不存在(ar-P)")
	}

	// 获取用户的 permissions == 缓存

	permissions, errUserRole := partner_admin_permissions.GetAdminPermissionsByRoleIdFromDb(ur.Id, ur.IsSuperRole())
	// 如果没有查询到 直接返回
	if errUserRole != nil {
		return nil, app.NewError("m-a-u-P-0001-" + errUserRole.Error())
	}

	ur.permissions = permissions

	return ur.permissions, nil
}

/* ========================== 辅助操作 ============================ */

// @help
// @title 把当前角色的权限转成 map {k => v}
func (ur UserRoles) HelpPermissionToKV() (map[int64]string, error) {
	permissions, err := ur.Permissions()
	if err != nil {
		return nil, app.NewError(err)
	}

	returnData := make(map[int64]string)
	for k, item := range permissions {
		returnData[k] = item.Name
	}

	return returnData, nil
}

// @help
// @title 把当前角色的权限转成 切片 [id, id, id]
func (ur UserRoles) HelpPermissionToKey() ([]int64, error) {
	permissions, err := ur.Permissions()
	if err != nil {
		return nil, app.NewError(err)
	}

	returnData := make([]int64, 0)
	for k, _ := range permissions {
		returnData = append(returnData, k)
	}

	return returnData, nil
}

// @help
// @title 把当前角色的权限转成 map {k:k} [id:id, id:id, id:id]
func (ur UserRoles) HelpPermissionToKK() (map[int64]int64, error) {
	permissions, err := ur.Permissions()
	if err != nil {
		return nil, app.NewError(err)
	}

	returnData := make(map[int64]int64)
	for k, _ := range permissions {
		returnData[k] = k
	}

	return returnData, nil
}
